import router from '../router'
import store from '../store'
import {MessageBox} from 'element-ui'

/**
 * @author liubaohui
 * @desc 页面离开提示
 * @returns {Promise<any>}
 */
export default function backToList() {
  return new Promise((resolve, reject) => {
    if (!store.state.hasDetailChange) {
      resolve()
    } else {
      MessageBox.confirm('检测到未保存的内容，是否在离开前保存修改？', '离开提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '保存',
        cancelButtonText: '放弃修改',
        type: 'warning',
        customClass: 'mes_confirm'
      })
        .then(() => {
          if (router.currentRoute.matched.length !== 0 && router.currentRoute.matched[1].instances.default.save) {
            router.currentRoute.matched[1].instances.default.save()
          } else {
            reject(new Error('保存方法未找到'))
          }
        })
        .catch(action => {
          if (action === 'cancel') {
            store.commit('DEL_VISITED_VIEWS', router.currentRoute)
            store.commit('SetHasDetailChange', false)
            resolve()
          }
        })
    }
  })
}
